﻿package effects
{
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.external.ExternalInterface;
	import flash.filters.*;
	import flash.geom.*;
	import flash.net.URLRequest;
	public class Effect4 extends Effect
	{
		private var url:String = "assets/dot0.png";
	    private var loader:Loader = new Loader();
	    private var matrix:Matrix;
	    private var filterMatrix:Matrix = new Matrix();
	    private var bitmap:BitmapData;
	    private var filter:Sprite; 
		public function Effect4() 
		{
			cacheAsBitmap=true;
			var request:URLRequest = new URLRequest(url);
	            
		    loader.load(request);
		    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, draw);
		    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		    
		    filter = new Sprite;
		    filter.blendMode="overlay";
		    applyFilter(true);
		}
		public override function add():void
	    {
	    	addEventListener(Event.ENTER_FRAME,render);
	    }
	    public override function remove():void
	    {
	    	removeEventListener(Event.ENTER_FRAME,render);
				
	    	filterMatrix.tx=0;
	    	filterMatrix.ty=0;
	    	var c:Number=Math.random()*10;
	    	filterMatrix.invert();
	    	filterMatrix.rotate(Math.PI/c); 
	    }
		private function draw(e:Event):void
		{
			bitmap = new BitmapData(loader.width, loader.height, true,0xFF333333);
			bitmap.draw(loader, new Matrix(),new ColorTransform(1,1,1,.5,0,0,0,0),"multiply",null,true);
			
		    matrix = new Matrix();
		    //matrix.rotate(Math.PI/4);
		    //matrix.b=20;
		    //matrix.a=90
			// matrix.scale(.5,.5);
			with(graphics){
				beginBitmapFill(bitmap, matrix, true,true);
				drawRect(0, 0, Global._stage.stageWidth, Global._stage.stageHeight);
				endFill();
			}
			addEventListener(Event.ENTER_FRAME,render);
		}
		private function render(e:Event):void
		{
			with(graphics){
				clear();
				beginBitmapFill(bitmap, matrix, true,true);
				drawRect(0, 0, Global._stage.stageWidth, Global._stage.stageHeight);
				endFill();
			}
			applyFilter();
		}
		private function applyFilter(a:Boolean=false):void
		{
			filterMatrix.tx+=4;
			
			filter.graphics.clear();
			filter.graphics.beginGradientFill("linear",[0x99ff00,0xff6699,0x66ffff],[1,1,1],[0, 125, 255],filterMatrix,"reflect","Linear_RGB",0);
			filter.graphics.drawRect(0,0,Global._stage.stageWidth,Global._stage.stageHeight);
			filter.graphics.endFill();
			if(a)
				addChild(filter);
		}
		private function ioErrorHandler(event:IOErrorEvent):void {
			ExternalInterface.call("alert","Unable to load image: " + url);
	    }
	}
}
